package com.example.tourpal;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;

import com.example.tourpal.model.Journey;
import com.example.tourpal.model.LocalDataLoader;
import com.example.tourpal.model.LocalDataLoader.DeleteDataLishenter;
import com.example.tourpal.model.LocalDataLoader.UserJourneyLishenter;
import com.example.tourpal.widget.PlanAdapter;

public class MyPlanActivity extends Activity {

	private static final String UNDER_LINE = "-";

	public static final int RESULT_BACK = 13;

	private Context context;

	private ImageView back;
	private ListView mePlanListView;

	// Data
	private PlanAdapter mePlanAdapter;
	private List<HashMap<String, Object>> resultPlanList;
	private List<Journey> journeyList;

	private SimpleDateFormat sFormat;
	private SimpleDateFormat tFormat;

	// private User mUser;
	private LocalDataLoader loader;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		context = this;

		setContentView(R.layout.me_plan_view);

		sFormat = new SimpleDateFormat(getText(R.string.date_format_1)
				.toString(), Locale.getDefault());
		tFormat = new SimpleDateFormat(getText(R.string.date_format_2)
				.toString(), Locale.getDefault());

		mePlanListView = (ListView) findViewById(R.id.mePlan);

		getMePlan();

		back = (ImageView) findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				finish();
			}
		});
		mePlanListView
				.setOnItemLongClickListener(new OnItemLongClickListener() {

					@Override
					public boolean onItemLongClick(AdapterView<?> parent,
							View view, final int position, long id) {
						Builder builder = new Builder(MyPlanActivity.this);
						builder.setIcon(R.drawable.message_delete_icon);
						builder.setTitle(getResources().getString(
								R.string.alertdialog_title));
						String msg = String.format(
								getResources().getString(
										R.string.delete_journey_message),
								resultPlanList.get(position).get("planName"));
						builder.setMessage(msg);
						builder.setPositiveButton(
								getResources().getString(
										R.string.alertdialog_ok),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										loader.publishDeleteJourney(
												(int) (resultPlanList
														.get(position)
														.get("planId")),
												new DeleteDataLishenter() {

													@Override
													public void requestDeleteResult(
															int code) {
														resultPlanList
																.remove(position);
														mePlanAdapter
																.notifyDataSetChanged();
													}
												});
									}
								});
						builder.setNegativeButton(
								getResources().getString(
										R.string.alertdialog_cancel),
								new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog,
											int which) {
									}
								});
						AlertDialog alertDialog = builder.create();
						alertDialog.setCanceledOnTouchOutside(false);
						alertDialog.show();
						return true;
					}

				});
	}

	protected void getMePlan() {

		resultPlanList = new ArrayList<HashMap<String, Object>>();

		loader = new LocalDataLoader(context);
		loader.startLoadUserJourney(new UserJourneyLishenter() {

			@Override
			public void requestUserJourneyList(List<Journey> journeys) {
				journeyList = journeys;

				for (Journey journey : journeys) {
					HashMap<String, Object> itemHashMap = new HashMap<String, Object>();
					itemHashMap.put("planId", journey.getId());
					itemHashMap.put("followSign", journey.getIspublic());
					itemHashMap.put("planName", journey.getName());
					try {
						String start = tFormat.format(sFormat.parse(journey
								.getStartTime()));
						String end = tFormat.format(sFormat.parse(journey
								.getEndTime()));
						itemHashMap.put("planDate", start + UNDER_LINE + end);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					itemHashMap.put("planHint", journey.getDestination());
					itemHashMap.put("goodCnt", journey.getPraiseNum());
					itemHashMap
							.put("commentCnt", 0/* journey.getCommentNum() */);
					resultPlanList.add(itemHashMap);
				}

				mePlanAdapter = new PlanAdapter(context, resultPlanList);
				mePlanListView.setAdapter(mePlanAdapter);
			}

		});
	}

	public boolean isNetworkAvailable() {
		ConnectivityManager cm = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (cm == null) {
		} else {// cm.getActiveNetworkInfo().isAvailable();
			NetworkInfo[] info = cm.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub
		super.finish();

		overridePendingTransition(R.anim.main_enter, R.anim.sub_exit);
	}

	public void editPlan(int index) {
		Intent intent = new Intent();
		intent.putExtra("editJourney", journeyList.get(index));
		setResult(RESULT_BACK, intent);
		finish();
	}
}
